package com.app.micaihu.view.login.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.infor.UserInfor
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.manager.AppConfigManager
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.app.micaihu.view.login.utils.CloseLoginActivityUtils
import com.app.micaihu.view.user.userinfo.activity.WebActivity
import com.app.utils.biz.Biz
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tuo.customview.VerificationCodeView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.login_last_activity.*
import kotlinx.android.synthetic.main.login_phone_code_activity.*
import kotlinx.android.synthetic.main.login_phone_code_activity.ivBack
import kotlinx.android.synthetic.main.login_phone_code_activity.tvLoginCode
import kotlinx.android.synthetic.main.login_phone_code_activity.tvPrivacyProtocol
import kotlinx.android.synthetic.main.login_phone_code_activity.tvUserProtocol
import java.util.concurrent.TimeUnit

/**
 * Created by Guo on 2016/7/14.
 *  接受验证码的页面
 */
class PhoneCodeActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View {

    override fun getPresenter() = LogInPresenter()

    override fun getLayoutId() = R.layout.login_phone_code_activity

    override fun getBundle(bundle: Bundle) {
        phone = bundle.getString(Config.Extra.phone, "")
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.extras?.let {
            phone = it.getString(Config.Extra.phone, "")
        }
    }


    var phone: String = ""
    private var mdDisposable: Disposable? = null

    @SuppressLint("SetTextI18n")
    override fun setData() {
        BarUtils.addMarginTopEqualStatusBarHeight(ivBack)
        val military = Biz.instance.military
        if (StringUtils.isEmpty(military)) {
            tvTitle.text = "欢迎来到迷彩虎"
        } else {
            tvTitle.text = "欢迎来到迷彩虎${Config.militaryList[military.toInt() - 1]}"
        }
        tvPhone.text = phone
        startTimer()
        tvPhone.postDelayed({
            KeyboardUtils.showSoftInput(verificationCodeView.editText)
        }, 500)

    }

    override fun addListeners() {
        ivBack.setOnClickListener {
            finish()
        }
        tvLoginCode.setOnClickListener {
            startTimer()
        }
        verificationCodeView.setInputCompleteListener(object : VerificationCodeView.InputCompleteListener {
            override fun inputComplete() {
                val code = verificationCodeView.inputContent
                if (code.length == 4) {
                    //登录
                    mPresenter?.captchaLogin(phone, code)
                }
            }

            override fun deleteContent() {

            }

        })

        tvUserProtocol.setOnClickListener {
            //用户协议
            val userAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.userAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, userAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
        tvPrivacyProtocol.setOnClickListener {
            //隐私协议
            val privateAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.privateAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, privateAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
    }

    @SuppressLint("SetTextI18n", "AutoDispose")
    private fun startTimer() {
        val count = 60
        mdDisposable?.dispose()
        //从1开始发射60个数字为：0-60依次输出，延时0s执行，每1s发射一次。
        mdDisposable = Flowable.intervalRange(1, count.toLong(), 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { aLong: Long ->
                    tvLoginCode.isEnabled = false
                    tvLoginCode.text = (count - aLong).toString() + "s后重新获取"
                }.doOnComplete {
                    //倒计时完毕置为可点击状态
                    tvLoginCode.isEnabled = true
                    tvLoginCode.text = "获取验证码"
                }.subscribe()
    }

    override fun handleCaptchaLogin(login: BaseBean<UserInfor?>?) {
        if (login == null) {
            ToastUtils.showShort(getString(R.string.net_error))
            mdDisposable?.dispose()
            tvLoginCode.isEnabled = true
            tvLoginCode.text = "获取验证码"
        } else {
            if (login.isSuccess()) {
                login.data?.let {
                    //设置用户信息
                    UserInforManager.getInstance().userInfor = it//设置用户信息
                    //保存到本地
                    UserInforManager.getInstance().saveUserInfor(it)
                    //拉取任务数据
                    UserInforManager.getInstance().getUserTask(this, true)
                    LiveEventBus.get(Config.EventBus.loginSuccess).post(true)
                    if (it.mobile.isEmpty()) {
                        val bundle = Bundle()
                        bundle.putBoolean(Config.Extra.showSkip, true)
                        enterPager(BindPhoneActivity::class.java, bundle)
                    }
                    CloseLoginActivityUtils.closeAllLoginActivity()
                }
            } else {
                ToastUtils.showShort(login.msg)
                mdDisposable?.dispose()
                tvLoginCode.isEnabled = true
                tvLoginCode.text = "获取验证码"
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mdDisposable?.dispose()
    }
}